<template>
  <el-dialog
    class="basic-dialog"
    :model-value="visible"
    :title="pageTitle"
    :width="480"
    :close-on-click-modal="!loading"
    :close-on-press-escape="!loading"
    :show-close="!loading"
    @closed="handleClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="92"
      label-position="left"
      require-asterisk-position="right"
    >
      <el-form-item label="账号" prop="username" required>
        <el-input
          v-model="formData.username"
          :disabled="!!props.record?.id"
          maxlength="18"
          show-word-limit
          autocomplete="off"
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="!record" label="密码" prop="password">
        <basic-password-input
          :key="passwordKey"
          v-model="formData.password"
          autocomplete="off"
          default-type="text"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" required>
        <el-input
          v-model="formData.email"
          maxlength="200"
          placeholder="请输入邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址1" prop="ns1" required>
        <el-select
          v-model="formData.ns1"
          fit-input-width
          placeholder="请选择DNS地址"
        >
          <el-option
            v-for="item in nsList"
            :key="item.label"
            :label="item.label"
            :value="item.value"
            :disabled="item.value === formData.ns2"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地址2" prop="ns2" required>
        <el-select
          v-model="formData.ns2"
          fit-input-width
          placeholder="请选择DNS地址"
        >
          <el-option
            v-for="item in nsList"
            :key="item.label"
            :label="item.label"
            :value="item.value"
            :disabled="item.value === formData.ns1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分组" prop="group_id">
        <el-select v-model="formData.group_id" fit-input-width>
          <el-option label="暂不分组" value="0"></el-option>
          <el-option
            v-for="item in groupOpts"
            :key="item.label"
            :label="item.label"
            fit-input-width
            :value="item.value"
            :disabled="item.value === formData.ns1"
          >
            <text-ell :content="item.label" />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          maxlength="200"
          resize="none"
          :autosize="{ minRows: 1, maxRows: 3 }"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <basic-switch v-model="formData.status"></basic-switch>
      </el-form-item>
      <el-form-item label="对外接口" prop="api_status">
        <basic-switch v-model="formData.api_status"></basic-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :loading="loading" type="primary" @click="handleSubmit">
        确定
      </el-button>
      <el-button :loading="loading" @click="emit('update:visible', false)"
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { omit } from 'lodash-es'

import type { UserModel } from '@/apis/model/user'
import { useSelectRemote } from '@/hooks/useSelectRemote'
import ToastUtils from '@/utils/toast'

import useEditUserForm from '../hooks/useEditUserForm'

interface IProps {
  visible: boolean
  record?: UserModel | undefined | null
  loading?: boolean
}

interface IEmits {
  // 更新 显示状态
  (event: 'update:visible', value: boolean): void
  // 更新 loading状态
  (event: 'update:loading', value: boolean): void
  // 更新 数据
  (event: 'update:record', value?: UserModel): void
  // 通知上层更新
  (event: 'reload'): void
}

const emit = defineEmits<IEmits>()
const props = withDefaults(defineProps<IProps>(), {})
const pageTitle = computed(() => (props.record?.id ? '编辑用户' : '添加用户'))
const passwordKey = ref(Date.now())

const { formRef, formData, formRules } = useEditUserForm()

/**
 * 获取DNS服务器列表，用于下拉选
 */
const { remoteMethod: getDnsServerList, opts: nsList } = useSelectRemote(
  dnsServerListApi,
  {
    valueKey: 'id',
    labelKey: 'addr',
    queryKey: ''
  }
)

/**避免显示id */
const setNs = () => {
  getDnsServerList('').then(() => {
    if (!props.record?.id) {
      if (nsList.value.length) {
        formData.ns1 = nsList.value[0].value
        formData.ns2 = nsList.value[1].value || ''
      }
    } else {
      const assign_ns_list = props.record?.assign_ns_list || []
      formData.ns1 = assign_ns_list[0]?.id ?? ''
      formData.ns2 = assign_ns_list[1]?.id ?? ''
    }
  })
}

setNs()

watch(
  () => props.visible,
  visible => {
    if (!visible) {
      return
    }
    setNs()
  }
)

/**
 * 分组列表
 */
const { remoteMethod: getUserGroupList, opts: groupOpts } = useSelectRemote(
  userGroupListApi,
  {
    valueKey: 'id',
    labelKey: 'name',
    queryKey: ''
  }
)

getUserGroupList('')

watch(
  () => props.visible,
  visible => {
    if (visible) {
      getUserGroupList('')
    }
  }
)

/**
 * 保存方法
 */
const handleSubmit = async () => {
  await formRef.value?.validate()

  emit('update:loading', true)
  const data = {
    ...omit(formData, ['ns1', 'ns2']),
    ns_id_list: [formData.ns1, formData.ns2]
  }
  try {
    if (!props.record?.id) {
      await postUserApi(data)
    } else {
      const params = { ...data, id: props.record.id, password: void 0 }
      await putUserApi(params)
    }
    emit('reload')
    emit('update:visible', false)
    ToastUtils.success(props.record?.id ? '修改成功' : '创建成功')
  } finally {
    emit('update:loading', false)
  }
}

/**
 * @description dialog 打开事件
 */
const handleDialogOpen = () => {
  if (props.record?.id) {
    formData.username = props.record.username!
    formData.email = props.record.email!
    if (props.record.assign_ns_list) {
      formData.ns1 = props.record.assign_ns_list[0].id!
      formData.ns2 = props.record.assign_ns_list[1].id!
    }
    formData.group_id = props.record.group_id!
    formData.remark = props.record.remark!
    formData.status = props.record.status!
    formData.api_status = props.record.api_status!
  }
}

/**
 * @description dialog 关闭前事件
 */
const handleClosed = () => {
  formRef.value?.resetFields()
  passwordKey.value = Date.now()
  emit('update:record', undefined)
  emit('update:visible', false)
}
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
